package dev.alm.cqtakeoutservice.interceptor;

import dev.alm.cqtakeoutservice.utils.JedisUtil;
import dev.alm.cqtakeoutservice.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("login interceptor");
        String token = request.getHeader("cq-token");
        log.info("token: " + token);
        if (Strings.isEmpty(token)) {
            log.info("token is empty");
            throw new Exception("token is empty");
        }
        String username = JwtUtil.parseJwtToken(token);
        String cacheToken = JedisUtil.get(username);
        if (Strings.isEmpty(cacheToken) || !token.equals(cacheToken)) {
            log.info("token is invalid");
            throw new Exception("token is invalid");
        }
        return true;
    }

}
